/**
 * Created with JetBrains WebStorm.
 * User: gcw
 * Date: 14-6-18
 * Time: 下午5:19
 * To change this template use File | Settings | File Templates.
 */

//记录在线用户
var userList=[];

var all_num = 0;


exports.createCon = function(socket){
//    用户进入页面
    socket.on('add', function(data){
        socket.user = {};
        socket.user.name = "";
        socket.user.ip = socket.handshake.address.address;
        socket.emit("add", {num: all_num});
        userList.push(socket);
    });
//    用户加入聊天
    socket.on("join", function(data){
        var name = data.name;
        var num = nameIsExist(name);
        if(num !== true){
            all_num++;
            socket.user.name = name;
            socket.emit("join",{status: true, name: name, ip: socket.user.ip} );
            var time = getTime();
            groupEmit("join-us", {name: name, ip: socket.user.ip, num: all_num, time: time});
        }else{
            socket.emit("join", {status: false});
        }
    });
    //  用户退出聊天
    socket.on("exit", function(data){
        if(socket.user !== undefined){
            if( socket.user.name != ""){
                all_num--;
                var time = getTime();
                groupEmit("exit-us", {name: socket.user.name, ip: socket.user.ip, num: all_num, time: time});
            }
            for(var i = 0, len = userList.length; i < len; i++){
                console.log();
                if(socket === userList[i]){
                    userList.splice(i, 1);
                    break;
                }
            }
            socket = null;
        }

    });
//  监听用户发送消息
    socket.on("msg", function(data){
        var time = getTime();
        groupEmit("msg", {name: socket.user.name, ip: socket.user.ip, time: time, content: data.content});
    });

};

//返回聊天页面
exports.returnTalk = function(req, res){
    res.sendfile("frontend/html/talk.html")
};





//判断用户昵称是否已存在
function nameIsExist(name){
    var i = 0;
    var len = userList.length;
    while(i < len){
        if(userList[i].user.name == name){
            return true;
        }
        i++;
    }
    return len;
};

//群发消息
function groupEmit(url, data){
    for(var i = 0, len = userList.length; i < len; i++){
         userList[i].emit(url, data);
    }
};

//获取当前时间
function getTime(){
    var time = new Date();
    return time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds();
}
